package org.weiyonghua.dao;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

/**
 * Created by weiyonghua on 2017/3/23.
 */
@Setter @Getter @Repository
public class BaseDao<T> {
    @Autowired
    @Qualifier("primaryJdbcTemplate")
    JdbcTemplate jdbcTemplate;

    public <T> T queryForObjectNullable(String sql, RowMapper<T> rowMapper, Object... args) throws DataAccessException {
        try {
            return jdbcTemplate.queryForObject(sql, rowMapper, args);
        } catch (DataAccessException e) {
            if (e instanceof IncorrectResultSizeDataAccessException && ((IncorrectResultSizeDataAccessException) e).getActualSize() == 0) {
                return null;
            }
            throw e;
        }
    }
}
